<template>
  <div>
    <el-dialog
      :visible="visible"
      :title="title"
      :width="width"
      append-to-body
      @close="close"
      @closed="closed"
    >
      <el-form
        ref="depotDataForm"
        :model="depotDataForm"
        :rules="rules"
        :disabled="operation === 0"
        label-width="125px"
        label-position="right"
        label-suffix=":"
      >
        <h3>{{ $t("backOrderLang.backInfo") }}</h3>
        <el-form-item v-if="operation !== 1" :label="$t('depotLang.depotStatus')">
          <div style="margin-left: 5px">{{ $t("statusLang." + getTitleByValue(backStatusOptions, depotDataForm.returnStatus)) }}</div>
        </el-form-item>
        <el-form-item prop="returnType" :label="$t('backOrderLang.backType')">
          <template>
            <el-radio-group v-model="depotDataForm.returnType">
              <el-radio
                v-for="item in backTypeOptions"
                :key="item.value"
                :label="item.value"
              >{{ $t("statusLang." + item.title) }}
              </el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
        <el-form-item :label="$t('backOrderLang.harvestWarehouse')" prop="receiptDepotId">
          <template>
            <el-radio-group v-model="depotDataForm.receiptDepotId">
              <el-radio
                v-for="item in depotList"
                :key="item.value"
                :label="item.value"
              >{{ item.title }}
              </el-radio>
            </el-radio-group>
          </template>
        </el-form-item>

        <el-form-item :label="$t('backOrderLang.backOrderNum')" prop="returnNo">
          <el-input
            v-model="depotDataForm.returnNo"
            :placeholder="$t('pleaseEnter')"
            clearable
            style="width: 50%"
          />
        </el-form-item>
        <el-form-item :label="$t('backOrderLang.originalOutNo')" prop="trackingNo">
          <el-input
            v-model="depotDataForm.trackingNo"
            :placeholder="$t('pleaseEnter')"
            clearable
            style="width: 50%"
          />
          <el-button
            type="primary"
            size="small"
            :loading="submitLoading"
            style="margin-left: 30px"
            @click="handleSelect"
          >{{ $t("query") }}</el-button>
        </el-form-item>
        <div v-if="operation !==1 || isVisible">
          <el-form-item :label="$t('goodsSKULang.customerCode')" prop="customCode">
            <span>{{ depotDataForm.customCode }}</span>
          </el-form-item>
          <el-form-item :label="$t('backOrderLang.originalMaterialFlowOrderNum')" prop="providerTrackingNo">
            <span>{{ depotDataForm.providerTrackingNo }}</span>
          </el-form-item>
          <el-form-item :label="$t('backOrderLang.originalOMSNum')" prop="originalOMSNum">
            <span>{{ depotDataForm.trackingNo }}</span>
          </el-form-item>
          <!--产品信息-->
          <el-form-item :label="$t('goodsSKULang.baseSkuInfoDTO')">
            <el-table :data="depotDataForm.skuListData" border class="mt-10">
              <el-table-column
                :label="$t('goodsSKULang.skuCode')"
                prop="skuCode"
                align="center"
              />
              <el-table-column
                :label="$t('goodsSKULang.goodsName')"
                prop="goodsName"
                align="center"
              />
              <el-table-column
                :label="$t('goodsSKULang.skuNum')"
                prop="skuNum"
                align="center"
              />
              <el-table-column
                :label="$t('operation')"
                width="100"
                align="center"
                fixed="right"
              >
                <template slot-scope="scope">
                  <el-button type="text" @click="handleDelete(scope.row)">
                    {{ $t("delete") }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </div>
        <!--产品信息-->
        <el-form-item :label="$t('backOrderLang.preArrivalTime')" prop="preArrivalDate">
          <el-date-picker
            v-model="depotDataForm.preArrivalDate"
            type="date"
            value-format="timestamp"
            style="width: 350px"
            clearable
            :placeholder="$t('selectDate')"
          >
            />
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('backOrderLang.backReason')" prop="returnReason">
          <el-input
            v-model="depotDataForm.returnReason"
            :placeholder="$t('pleaseEnter')"
            clearable
            style="width: 50%"
          />
        </el-form-item>
        <el-form-item :label="$t('backOrderLang.operateType')" prop="operateType">
          <el-checkbox-group
            v-model="depotDataForm.operateType"
            style="padding: 5px 15px;"
            @change="handleCheckboxChange"
          >
            <el-checkbox
              v-for="item in operateTypeOptions"
              :key="item.value"
              :label="item.value"
            >{{ $t("backOrderLang." + item.title) }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div v-if="operation !== 1">
        <h3>{{ $t("backOrderLang.backInfo") }}</h3>
        <template>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane :label="$t('unownedGoodsLang.pic')" name="pictureUrls">
              <div class="image-list">
                <el-image
                  v-for="(image, index) in urls"
                  :key="index"
                  :src="image"
                  class="uploaded-image"
                  :preview-src-list="urls"
                  fit="cover"
                  @dblclick.native="handleDoubleClick(index)"
                />
              </div>
            </el-tab-pane>
            <!--            <el-tab-pane :label="$t('backOrderLang.unboxingVideo')" name="video">-->
            <!--              <template>-->
            <!--                <div>-->
            <!--                  &lt;!&ndash; 使用 Element UI 的卡片组件来包裹视频 &ndash;&gt;-->
            <!--                  <el-card class="box-card">-->
            <!--                    <video width="100%" controls>-->
            <!--                      <source :src="videoUrl" type="video/mp4">-->
            <!--                      您的浏览器不支持Video标签。-->
            <!--                    </video>-->
            <!--                  </el-card>-->
            <!--                </div>-->
            <!--              </template>-->
            <!--            </el-tab-pane>-->
            <el-tab-pane :label="$t('outboundOrderLang.operationRecord')" name="record">
              <template>
                <el-table :data="operateData" style="width: 100%" border class="mt-10">
                  <el-table-column
                    :label="$t('tableIndex')"
                    type="index"
                    align="center"
                    width="100"
                  />
                  <el-table-column
                    prop="orderStatusName"
                    :label="$t('harvestLang.operationNode')"
                    width="180"
                  />
                  <el-table-column
                    prop="createdUserName"
                    :label="$t('goodsSKULang.operator')"
                    width="180"
                  />
                  <el-table-column
                    prop="gmtCreated"
                    :label="$t('operationDate')"
                  />
                </el-table>
              </template>
            </el-tab-pane>
          </el-tabs>
        </template>
      </div>
      <div v-if="operation === 1" slot="footer">
        <el-button type="warning" plain size="small" @click="close">{{
          $t("cancel")
        }}</el-button>
        <el-button
          type="primary"
          size="small"
          :loading="submitLoading"
          @click="handleSubmit"
        >{{ $t("submit") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import to from 'await-to-js'
import { backStatusOptionDict, backTypeOptionDict, operationTypeOptionDict } from '@/utils/dictData'
import { getDictOptionList, getTitleByValue } from '@/utils/dictUtils'
import { getDepotList } from '@/api/business/depotManage/depot'
import { queryOutboundOrderPageList } from '@/api/business/outboundManage/invoicing'
import { returnAdd, getInfo } from '@/api/business/operateManage/return'

export default {
  name: 'DepotForm',
  props: {
    value: {
      type: Number,
      default: undefined
    },
    visible: {
      type: Boolean,
      default: undefined
    },
    operation: {
      type: Number,
      default: 0 // 0查看 1新增 2修改
    },
    title: {
      type: String,
      default: null
    },
    width: {
      type: String,
      default: '70%'
    }
  },
  data() {
    return {
      isZoomed: false,
      zoomedIndex: null,
      operateData: [],
      depotList: [],
      // videoUrl: 'https://v.youku.com/v_show/id_XNTk1MDg3MzE2MA==.html?spm=a2hja.14919748_WEBHOME_NEW.drawer2.d_zj1_3&s=fabd799ef8f546219853&scm=20140719.rcmd.35027.show_fabd799ef8f546219853',
      urls: [],
      activeName: 'pic',
      isVisible: false,
      backStatusOptions: getDictOptionList(backStatusOptionDict),
      backTypeOptions: getDictOptionList(backTypeOptionDict),
      operateTypeOptions: getDictOptionList(operationTypeOptionDict),
      operateType: [],
      harvestWarehouseOptions: [],
      submitLoading: false,
      getTitleByValue: getTitleByValue,
      depotDataForm: {
        returnType: null,
        receiptDepotId: null,
        returnNo: null,
        trackingNo: null,
        customId: null,
        providerTrackingNo: null,
        platformNo: null,
        skuListData: [],
        preArrivalDate: null,
        returnReason: null,
        operateType: []
      },
      rules: {
        returnType: {
          required: true,
          message: this.$t('pleaseSelect'),
          trigger: 'change'
        },
        receiptDepotId: {
          required: true,
          message: this.$t('pleaseSelect'),
          trigger: 'change'
        },
        returnNo: {
          required: true,
          message: this.$t('pleaseEnter'),
          trigger: 'blur'
        },
        trackingNo: {
          required: true,
          message: this.$t('pleaseEnter'),
          trigger: 'blur'
        },
        customId: {
          required: true,
          message: this.$t('required'),
          trigger: 'blur'
        },
        providerTrackingNo: {
          required: true,
          message: this.$t('required'),
          trigger: 'blur'
        },
        platformNo: {
          required: true,
          message: this.$t('required'),
          trigger: 'blur'
        },
        preArrivalDate: {
          required: true,
          message: this.$t('pleaseSelect'),
          trigger: 'blur'
        },
        returnReason: {
          required: true,
          message: this.$t('pleaseEnter'),
          trigger: 'blur'
        },
        operateType: {
          required: true,
          message: this.$t('pleaseSelect'),
          trigger: 'change'
        }
      }
    }
  },
  watch: {
    value: {
      handler(newVal, oldVal) {
        if (newVal != null && newVal !== undefined && newVal !== oldVal) {
          this.getData()
        }
      }
    }
  },
  created() {
    this.getData()
    this.getDepotList()
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event)
    },
    handleDoubleClick(index) {
      if (this.isZoomed && this.zoomedIndex === index) {
        // 如果已经放大，缩小回原尺寸
        this.isZoomed = false;
        this.zoomedIndex = null;
      } else {
        // 放大图片
        this.isZoomed = true;
        this.zoomedIndex = index;
      }
    },
    // 仓库下拉列表
    async getDepotList() {
      const { data } = await getDepotList()
      this.depotList = data
      console.log(data)
    },
    async getData() {
      if (!this.value || this.operation === 1) return
      const res = await getInfo({
        id: this.value
      })
      if (!res || res.data === null) return
      this.depotDataForm = res.data
      this.depotDataForm.skuListData = res.data.orderSkuBOList
      this.depotDataForm.trackingNo = res.data.outboundNo
      this.depotDataForm.returnNo = res.data.returnNo
      this.depotDataForm.operateType = res.data.operateType.split(',')
      this.operateData = res.data.warehouseManagementDTOS
      this.urls = res.data.pictureUrls
    },
    // 清空表单
    reset() {
      this.depotDataForm = {
        returnType: null,
        receiptDepotId: null,
        returnNo: null,
        trackingNo: null,
        customId: null,
        providerTrackingNo: null,
        platformNo: null,
        skuListData: [],
        preArrivalDate: null,
        returnReason: null,
        operateType: []
      }
      this.$refs.depotDataForm.resetFields()
    },
    // 查询
    async handleSelect() {
      // this.rules = this.selectRules
      console.log(this.depotDataForm)
      if (this.depotDataForm.returnType == null) {
        this.$message.error(this.$t('backOrderLang.tip1'))
        return
      }
      if (this.depotDataForm.receiptDepotId == null) {
        this.$message.error(this.$t('backOrderLang.tip2'))
        return
      }
      if (!this.depotDataForm.returnNo || this.depotDataForm.returnNo.length <= 0) {
        this.$message.error(this.$t('backOrderLang.tip3'))
        return
      }
      if (!this.depotDataForm.trackingNo || this.depotDataForm.trackingNo.length <= 0) {
        this.$message.error(this.$t('backOrderLang.tip4'))
        return
      }
      if (this.operation === 1) {
        const res = await queryOutboundOrderPageList({
          orderNo: this.depotDataForm.trackingNo
        })
        if (!res.data.dataList) {
          this.$message.error(this.$t('backOrderLang.tip5'))
          return
        }
        const basicData = res.data.dataList[0]
        this.depotDataForm.customCode = basicData.customerCode
        this.depotDataForm.providerTrackingNo = basicData.providerTrackingNo
        this.depotDataForm.platformNo = basicData.platformOrderNo
        this.depotDataForm.customId = basicData.customerId
        this.depotDataForm.trackingNo = basicData.trackingNo
        const tmpGoodsList = []
        basicData.goodsList.forEach(item => {
          tmpGoodsList.push({
            skuCode: item.goodsSkuCode,
            goodsName: item.goodsName,
            skuNum: item.goodsQuantity,
            skuId: item.goodsSkuId,
            skuLength: item.skuLength,
            skuHeight: item.skuHeight,
            skuWeight: item.skuWeight,
            skuWidth: item.skuWidth
          })
        })
        this.depotDataForm.skuListData = tmpGoodsList
        this.isVisible = true
      }
    },
    // 删除表格内容
    async handleDelete(row) {
      const rowIndex = this.depotDataForm.skuListData.findIndex(item => item.goodsSkuId === row.goodsSkuId)
      // 如果找到，移除这一行
      if (rowIndex !== -1) {
        this.depotDataForm.skuListData.splice(rowIndex, 1)
      }
    },
    // 提交
    async handleSubmit() {
      if (this.depotDataForm.skuListData.length <= 0) {
        this.$message.error(this.$t('backOrderLang.tip5'))
        return
      }
      const [err] = await to(this.$refs.depotDataForm.validate())
      if (err === null) {
        if (this.operation === 1) {
          this.depotDataForm.orderSkuBOList = this.depotDataForm.skuListData
          // 原物流单号
          this.depotDataForm.outboundNo = this.depotDataForm.trackingNo
          delete this.depotDataForm.customCode
          delete this.depotDataForm.skuListData
          delete this.depotDataForm.trackingNo
          this.depotDataForm.operateType = this.depotDataForm.operateType.join(',')
          // 新增
          const res = await returnAdd(this.depotDataForm)
          if (res.data === null && res.returnCode === 10000) {
            this.$message.success(this.$t('addSuccess'))
            this.$emit('close')
            this.$emit('update:operation', 2)
            // this.reset()
          } else {
            this.$message.error(res.returnMsg)
          }
        }
      }
    },
    // 复选框选中的值
    async handleCheckboxChange(data) {
      console.log(data)
      this.depotDataForm.operateType = data
    },
    // 关闭
    close() {
      this.$emit('close')
      this.isVisible = false
    },
    closed() {
      this.isVisible = false
      this.reset()
    }
  }
}
</script>

<style>
.uploaded-image {
  width: 100px;
  height: 100px;
  margin: 5px;
  cursor: pointer; /* 鼠标指针样式 */
  transition: transform 0.3s ease; /* 平滑过渡效果 */
}
.uploaded-image.zoomed {
  transform: scale(2); /* 放大比例 */
  z-index: 1000;
}
.image-list {
  display: flex;
  flex-wrap: wrap;
}
</style>
